package cn.wolfcode.rbac.service.impl;

import cn.wolfcode.rbac.domain.Department;
import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.mapper.EmployeeMapper;
import cn.wolfcode.rbac.query.EmployeeQueryObject;
import cn.wolfcode.rbac.query.PageResult;
import cn.wolfcode.rbac.query.QueryObject;
import cn.wolfcode.rbac.service.IEmployeeService;
import cn.wolfcode.rbac.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void saveOrUpdate(Employee employee,Long[] roleIds) {
        if (employee.getId()!=null){
            employeeMapper.updateByPrimaryKey(employee);

            employeeMapper.deleteEmployeeAndRoleRelation(employee.getId());
        }else {
            employeeMapper.insert(employee);
        }

        //添加新的employee_role关系
        if(roleIds != null){
            for(Long roleId : roleIds){
                employeeMapper.addEmployAndRoleRelation(employee.getId(),roleId);
            }
        }
    }

    @Override
    public void delete(Long id) {
        employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Employee getOne(Long id) {
        Employee employee = employeeMapper.selectByPrimaryKey(id);
        return employee;
    }

    @Override
    public List<Employee> listAll() {
        List<Employee> employees = employeeMapper.selectAll();
        return employees;
    }


    public PageResult query(EmployeeQueryObject qo) {
        //查询总条数
        int totalCount = employeeMapper.queryForCount(qo);
        //查询带有分页效果的结果集
        if(totalCount == 0){
            //查不出数据，调用的是pageResult类中的缺参构造器
            return new PageResult(qo.getCurrentPage(),qo.getPageSize());
        }

        List<Employee> data = employeeMapper.queryForList(qo);
        return new PageResult(data,totalCount,qo.getCurrentPage(),qo.getPageSize());
    }

    @Override
    public void login(String username,String password){
        //根据账号和密码上数据库去查询是否有数据
        //如果用户输入的账号和密码是正确，上数据库查询employee是有值的
        Employee employee=employeeMapper.login(username,password);

        if(employee==null){
            throw new RuntimeException();
        }

        //把employee放到session中
        UserContext.setCurrent(employee);
    }
}
